package com.winit.issue.service;

import com.winit.common.CloudLinkSend.MqMsgType;
import com.winit.common.CloudLinkSend.MsgSend;
import com.winit.issue.manager.IssueManager;
import com.winit.issue.model.Issue;
import com.winit.issue.model.IssueRelation;
import com.winit.issue.model.IssueStatus;
import com.winit.issue.repository.IssueRelationRepository;
import com.winit.issue.repository.IssueRepository;
import com.winit.issue.repository.IssueRepositoryExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IssueServiceImpl implements IIssueService {

    @Autowired
    private IssueRelationRepository issueRelationRepository;
    @Autowired
    private IssueRepositoryExt issueRepositoryExt;
    @Autowired
    IssueManager issueManager;
    @Autowired
    IssueRepository issueRepository;
    @Autowired
    MsgSend msgSend;

    @Override
    public void refreshIssueRelationForReq(String reqId, List<String> issueIds) {
        this.issueRelationRepository.deleteByRelationIdAndType(reqId, "REQ");
        if(CollectionUtils.isEmpty(issueIds)){
            return;
        }
        List<IssueRelation> issueRelations = new ArrayList<>();
        for (String issueId : issueIds){
            IssueRelation issueRelation = new IssueRelation();
            issueRelation.setIssueId(issueId);
            issueRelation.setRelationId(reqId);
            issueRelation.setType("REQ");
            issueRelations.add(issueRelation);
            Issue issue = new Issue();
            issue.setId(issueId);
            issue.setStatus("PRD");
            issueManager.updateIssue(issue);
        }
        this.issueRelationRepository.save(issueRelations);
    }

    @Override
    public void operateForReqOnline(String reqId) {
        List<String> issueIds = this.issueRelationRepository.getAllIssueIdsByRelationIdAndType(reqId, "REQ");
        if (CollectionUtils.isEmpty(issueIds)){
            return;
        }
        for (String issueId : issueIds){
            Map map=new HashMap<>();
            int num = this.issueRelationRepository.countUnfinishedReqOfIssue(issueId);
            if (num <= 0){
                Issue update = new Issue();
                update.setId(issueId);
                update.setStatus(IssueStatus.COMPLETE);
                this.issueRepositoryExt.updateByPropertyNotNull(update);
                map.put("issueId",update.getId());
            }
            msgSend.sendIssueMsg(MqMsgType.ONLINE,map);
        }
    }
}
